<?php

namespace addons\helper\controller\wxapp\general;

use app\common\model\Attachment as AttachmentModel;
use addons\helper\controller\wxapp\Base;

class Attachment extends Base
{
    protected $searchFields = 'id,url';
    protected $config = [
        // 模型标题
        'model' => '附件',
        // 每页记录数
        'limit' => 10,
        // 默认排序字段
        'defaultSort' => 'id',
        // 默认排序方向
        'defaultOrder' => 'desc',
        // tab选项卡字段
        'tabField'        => 'mimetype',
        'search'            => true,
        'filter'            => true,
        'multi'             => true,
        'sort'              => true,
        // 搜索框默认文字
        'searchPlaceholder' => '输入ID或文件路径搜索',
        // 定义除主键外的其它字段：未定义的字段前台页面皆不展现；另外，'可编辑'=false时的字段在编辑页不展现
        // ‘字段名’ => ['字段标题','表单类型','可排序','可筛选','筛选语法','可查看', '可编辑','可添加']
        'field' => [
            'storage'     => ['存储位置', 'text', false,  true, '=', true, true, false],
            'url'         => ['物理路径', 'text', false,  true, 'LIKE', true, true, false],
            'fullurl'     => ['完整地址', 'text', false,  false, '', true, false, false],
            'imagetype'   => ['文件类型', 'text', true,  true, '=', true, true, false],
            'filesize'    => ['文件大小', 'number', true,  true, 'BETWEEN', true, true, false],
            'imageframes' => ['图片帧数', 'number', false,  false, '', true, true, false],
            'imagewidth'  => ['图片宽度', 'number', true,  true, '=', true, true, false],
            'imageheight' => ['图片高度', 'number', true,  true, '=', true, true, false],
            'createtime'  => ['创建时间', 'datetime', false, true, 'RANGE', true, true, false],
            'updatetime'  => ['更新时间', 'datetime', false, true, 'RANGE', true, true, false],
            'uploadtime'  => ['上传时间', 'datetime', true, true, 'RANGE', true, true, false],
            'extparam'    => ['透传数据', 'text', false,  false, '', true, true, false],
        ],
        // [可选]前端表单验证规则
        'rules' => [
            'imagewidth' => [
                'required'    => true
            ],
            'createtime' => [
                'required'    => true
            ],
            'storage' => [
                'required'    => true,
                'rangelength' => [3, 30]
            ]
        ],
        // [可选]前端表单自定义验证提示信息
        'rulesMessage' => [
            'imagewidth' => [
                'required'    => '必须填写图片宽度噢'
            ]
        ],
        // 规则URL定义：供前端访问的控制器各方法URL，并实现权限验证
        'auth' => [
            // 基本操作
            'add'  => [
                'name' => '添加',
                'url'  => 'general.attachment/add',
            ],
            'edit'  => [
                'name' => '编辑',
                'url'  => 'general.attachment/edit',
            ],
            // 凡属于列表页「批量」中的操作，请放到multi数组中,可指定color(选项文字颜色)和icon(图标)
            'multi' => [
                'del'  => [
                    'name'        => '删除',
                    'color'       => '#e74c3c',
                    'icon'        => 'fa-trash',
                    'url'         => 'general.attachment/del'
                ]
            ],
            // 凡属于编辑页「更多」中的操作，请放到more数组中，可指定color(选项文字颜色)
            'more' => [
                'del'  => [
                    'name'  => '删除',
                    'color' => '#e74c3c',
                    'url'   => 'general.attachment/del'
                ]
            ],
        ]
    ];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Attachment;
        $this->config['field'] = $this->formatField();
        $this->config['pk'] = $this->model->getPk() ? $this->model->getPk() : 'id';
    }
    /**
     * 首页
     */
    public function index()
    {
        $mimetypeList = AttachmentModel::getMimetypeList();

        $mimetypeQuery = [];
        $filter = $this->request->post('filter');
        $filterArr = (array) json_decode($filter, true);
        if (isset($filterArr['mimetype']) && preg_match("/[]\,|\*]/", $filterArr['mimetype'])) {
            $this->request->post(['filter' => json_encode(array_diff_key($filterArr, ['mimetype' => '']))]);
            $mimetypeQuery = function ($query) use ($filterArr) {
                $mimetypeArr = explode(',', $filterArr['mimetype']);
                foreach ($mimetypeArr as $index => $item) {
                    if (stripos($item, "/*") !== false) {
                        $query->whereOr('mimetype', 'like', str_replace("/*", "/", $item) . '%');
                    } else {
                        $query->whereOr('mimetype', 'like', '%' . $item . '%');
                    }
                }
            };
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
            ->where($mimetypeQuery)
            ->where($where)
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->where($mimetypeQuery)
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit ? $limit : $this->config['limit'])
            ->select();
        foreach ($list as $k => &$v) {
            $v['name'] = basename($v['url']);
            $v['fullurl'] = $this->cdnurl . $v['url'];
        }
        unset($v);

        $data = array('total' => $total, 'rows' => $list);

        $tabList[] = array('id' => 'all', 'name' => '全部');
        foreach ($mimetypeList as $k => $v) {
            $tabList[] = array('id' => $k, 'name' => $v);
        }
        $data = [
            'tabList'  => $tabList,
            'dataList' => $data,
            'config'   => $this->config
        ];
        $this->success('ok', $data);
    }
    /**
     * 删除
     */
    public function del()
    {
        $ids = $this->request->post('ids/a');
        if ($ids) {
            \think\Hook::add('upload_delete', function ($params) {
                $attachmentFile = ROOT_PATH . '/public' . $params['url'];
                if (is_file($attachmentFile)) {
                    @unlink($attachmentFile);
                }
            });
            $attachmentlist = $this->model->where('id', 'in', $ids)->select();
            foreach ($attachmentlist as $attachment) {
                \think\Hook::listen("upload_delete", $attachment);
                $attachment->delete();
            }
            $this->success('删除成功');
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
